<?php
require_once  '../classes/ConnectionDB.php';
require_once  '../classes/UtenteManager.php';
require_once  '../classes/ClasseManager.php';
require_once  '../classes/ClasseDataManager.php';
require_once '../classes/ErrorsManager.php';

$errors = array();
$db =ConnectionDB::getInstance()->connectToDB();

$classe = $_POST['classe'];
$sezione = $_POST['sezione'];
$indirizzo = $_POST['indirizzo'];

if($sezione=="")
    $errors[]='7';
if($indirizzo=="")
    $errors[]='8';

$str = $_POST['strValido'];

if(strlen($str)==0)
    $errors[]='9';

if(count($errors)>0)
{
    $resp = ErrorsManager::getInstance()->manageErrors($errors);
    header("Location:../portal/manageErrors.php?lista=" . $resp);
}
else
{
    if(!ClasseManager::getInstance()->existClass($db, $classe, $sezione, $indirizzo))
    {
        ClasseManager::getInstance()->insertClasse($db, $classe, $sezione, $indirizzo);

        $codiceClasse = ClasseDataManager::getInstance()->getLastClasseInserted($db);

        $tmp = explode("+", $str);
//        error_log("tmp : " . count($tmp));
        for($k=0;$k<count($tmp)-1;$k++)
        {
            $stud= explode("*", $tmp[$k]);
//            error_log("stud[0] " . $stud[0]. " stud[1] " . $stud[1]);
            $nome = $stud[0];
            $cognome = $stud[1];
            if($stud[2]!="")
                $email= $stud[2];
            else
                $email="";
            $username= $stud[3];
            $password = $stud[4];


            UtenteManager::getInstance()->insertStudente($db, $nome, $cognome,  $email, $codiceClasse, $username, $password);
            
            $result = UtenteDataManager::getInstance()->getLastCodiceStudente($db);
            UtenteDataManager::getInstance()->updateUsernameStudente($db, $result);
            if($email!="")
               UtenteManager::getInstance()->sendMailStudente($nome, $cognome, $email, $result, $password);
        }
        header("Location:nuovaClasse.php?flag=1");
    }
    else
        header("Location:nuovaClasse.php?flag=0");
}
?>
